package com.insyte.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;


import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ImageView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptor;


import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.insyte.R;

import com.insyte.activities.LoginActivity;
import com.insyte.activities.LoginVerifyPhoneActivity;
import com.insyte.activities.TabMainActivity;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.model.User;
import com.insyte.networks.ParserUtils;
import com.insyte.services.GPSTracker;
import com.insyte.utils.BitmapUtility;
import com.insyte.utils.CirleImageView;
import com.insyte.utils.Initialize;
import com.insyte.utils.ToastUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class HomeFragment extends Fragment {//implements LocationSource.OnLocationChangedListener{//implements OnMapReadyCallback {
    private LatLng tutorialsPoint = new LatLng(21.0115047, 105.8657009);
    private GoogleMap googleMap;
    private MapView mMapView;
    private AQuery aQuery;
    private ImageView img_info;
    private String url_set_location = "/location/:id?token=<token>"; // method PUT | param: lat , lng
    private String url_find_near = "/user/:id/friend/range?range=<range>&token=<token>"; // method GET
    private String url_default_find_near = "/user/:id/friend/range?token=<token>"; // method GET
    private String url_test_find_near = "http://104.238.152.185:3045/user/559a2f06923276c113b1c316/friend/range?range=10000000&token=68efd5fa5caca9c9b6bf9f51ab35393731cdfab28c022220790a4e59da43babd462bb28443c0";
    private User user;
    private Initialize initialize;
    private Map<String, Object> params;
    private ProgressDialog progressDialog;
    private Timer timer;
    private TimerTask timerTask;
    private Handler handler;
    public static int findResult = 0;
    TabMainActivity mainActivity;// = new TabMainActivity();
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
//    private List<String> string_users = new ArrayList<String>();
    private List<User> user_markers = new ArrayList<User>();

    GPSTracker gpsTracker;
    double latitude = 0;
    double longitude = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gpsTracker = new GPSTracker(getActivity());
        initialize = new Initialize(getActivity());
        params = new HashMap<String, Object>();
        mainActivity = new TabMainActivity();
        progressDialog = initialize.createProgressDialog("update location");
        aQuery = new AQuery(getActivity());
        user = InsyteApp.getInstance().getUser();
        url_set_location = Constants.URL_API + "/location/" + user.getId() + "?token=" + user.getToken();
        url_find_near = Constants.URL_API + "/user/" + user.getId() + "/friend/range?range=" + 25 + "?token=" + user.getToken();
        Log.d("userInfo:", user.getId() + "===" + user.getToken());
        url_default_find_near = Constants.URL_API + "/user/" + user.getId() + "/friend/range?token=" + user.getToken();
        creatOptionImg();
    }

    private View viewMarker;
    private ImageView marker;
    private CirleImageView img_circle;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        mMapView = (MapView) v.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);
        mMapView.onResume();// needed to get the map to display immediately
        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        getAndSetLocation();
        googleMap = mMapView.getMap();
        if (tutorialsPoint != null) {
            try {
                viewMarker = getActivity().getLayoutInflater().inflate(R.layout.item_marker, null);
                marker = (ImageView) viewMarker.findViewById(R.id.marker);
                img_circle = (CirleImageView) viewMarker.findViewById(R.id.img_circle);
                MarkerOptions marker = new MarkerOptions().position(tutorialsPoint).title("Test marker");
                //Bitmap bitmap1 = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.avatar_chat);
                //BitmapFactory.Options options = new BitmapFactory.Options();
                //Bitmap bitmap_resize = Bitmap.createScaledBitmap(bitmap1, 68, 68, false);
                //Bitmap bitmap2 = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.pin_male_blue);
                //Bitmap bitmap3 = overlay(bitmap_resize, bitmap2);
                Bitmap pin_custom = BitmapUtility.createDrawableFromView(getActivity(), viewMarker);
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(pin_custom);
                marker.icon(bitmapDescriptor);
                googleMap.addMarker(marker);
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(tutorialsPoint).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));
            } catch (NullPointerException e) {
                Log.e("NullPointerException", e.toString());
                e.printStackTrace();
            }
        }
        img_info = (ImageView) v.findViewById(R.id.img_info);
        img_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FindUserResultFragment fragment2 = new FindUserResultFragment();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container1, fragment2);
                fragmentTransaction.commit();
                findResult = 1;
                //mainActivity.updateTab(2);

            }
        });

        setEvent();

        return v;
    }

    private void getAndSetLocation() {
        if (gpsTracker.canGetLocation()) {
            latitude = gpsTracker.getLatitude();
            longitude = gpsTracker.getLongitude();
            Log.d("currentLatLng:", latitude + "----" + longitude);
            tutorialsPoint = new LatLng(latitude, longitude);
            if (initialize.checkNetwork()) {
                params.put("lat", latitude);
                params.put("lng", longitude);
                updateLocation();
            } else {
                initialize.showToast("Please check your network!");
            }
        } else {
            gpsTracker.showSettingsAlert();
        }
//        googleMap = mMapView.getMap();
//        if (tutorialsPoint != null) {
//            MarkerOptions marker = new MarkerOptions().position(tutorialsPoint).title("Hello Maps");
//            marker.icon(BitmapDescriptorFactory
//                    .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
//            googleMap.addMarker(marker);
//            CameraPosition cameraPosition = new CameraPosition.Builder()
//                    .target(tutorialsPoint).zoom(12).build();
//            googleMap.animateCamera(CameraUpdateFactory
//                    .newCameraPosition(cameraPosition));
//        }
    }

    private void updateLocation() {
        aQuery.ajax(url_set_location, params, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                if (result != null) {
                    Log.e("resutl", result);
                    Log.e("", url_default_find_near);
                    findUsersNear();
                }
            }
        }.method(AQuery.METHOD_PUT).header("Content-Type", "application/x-www-form-urlencoded"));
    }

    private void findUsersNear() {
        Log.e("run method", "findUsersNear");
        aQuery.ajax(url_default_find_near, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                if (result != null) {
                    Log.e("rsult find near", result);
                    try {
                        JSONObject js = new JSONObject(result);
                        if (js.has("code") && js.getInt("code") == 1) {
                            JSONObject js_data = js.getJSONObject("data");
                            JSONArray js_users = js_data.getJSONArray("users");
                            drawMarkerForUsers(js_users);
                        }
                    } catch (JSONException e) {
                        Log.e("JSONException", e.toString());
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    private int x;

    private void drawMarkerForUsers(final JSONArray js) {
        x = 0;
        handler = new Handler();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (x < js.length()) {
                            try {
                                String url_img_profile = "";
                                final JSONObject user = (JSONObject) js.get(x);
                                if (user.getString("profile_picture").equalsIgnoreCase("")) {
                                    url_img_profile = Constants.URL_API + "/images/avatars/4ed7cb30-24af-11e5-b21b-93670ff29b60_thumb.jpg";
                                } else {
                                    url_img_profile = Constants.URL_API + user.getString("profile_picture");
                                }
                                imageLoader.loadImage(url_img_profile, options, new ImageLoadingListener() {
                                    @Override
                                    public void onLoadingStarted(String imageUri, View view) {

                                    }

                                    @Override
                                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                                    }

                                    @Override
                                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                        JSONObject js_location = null;
                                        try {
                                            Log.e("x", x + "");
                                            js_location = user.getJSONObject("location");
                                            img_circle.setImageBitmap(loadedImage);

                                            if (user.getInt("friend_status") != 0) { // ket ban roi green
                                                marker.setImageResource(R.drawable.pin_female_green);
                                            } else {
                                                if (user.getString("gender").equalsIgnoreCase("Male")) { // chua ket ban nam blue
                                                    marker.setImageResource(R.drawable.pin_male_blue);
                                                } else { // chua ket ban nu pink
                                                    marker.setImageResource(R.drawable.pin_female_pink);
                                                }
                                            }

                                            tutorialsPoint = new LatLng(js_location.getDouble("lat"), js_location.getDouble("lng"));
                                            Log.e("lat", js_location.getDouble("lat") + "");
                                            Log.e("lng", js_location.getDouble("lng") + "");
                                            MarkerOptions marker_map = new MarkerOptions().position(tutorialsPoint).title("sdf");
                                            Bitmap pin_custom = BitmapUtility.createDrawableFromView(getActivity(), viewMarker);
                                            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(pin_custom);
                                            marker_map.icon(bitmapDescriptor);
                                            googleMap.addMarker(marker_map);
                                            User new_user_marker = new User();
                                            Gson gson = new Gson();
                                            new_user_marker = gson.fromJson(user.toString(), User.class);
                                            user_markers.add(new_user_marker);
//                                            string_users.add(user.toString());
                                            x++;

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onLoadingCancelled(String imageUri, View view) {

                                    }
                                });
                            } catch (JSONException e) {
                                Log.e("JSONException", e.toString());
                                e.printStackTrace();
                            } catch (NullPointerException e) {
                                Log.e("NullPointerException", e.toString());
                                e.printStackTrace();
                            } catch (Exception e) {
                                Log.e("Exception", e.toString());
                                e.printStackTrace();
                            }
                        } else {
                            timer.cancel();
                        }
                    }
                });
            }
        };
        timer.schedule(timerTask, 1000, 1000);
    }

    private void creatOptionImg() {
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .build();
        new DisplayImageOptions.Builder().imageScaleType(ImageScaleType.EXACTLY);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
    }


    private void setEvent() {
        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                try {
                    UserFragment userFragment = new UserFragment();

                    Bundle bundle = new Bundle();
                    String id_marker = marker.getId();
                    int id_user = Integer.parseInt(id_marker.replaceAll("m", ""));
//                bundle.putString(Constants.KEY_USER_MARKER, string_users.get(id_user));
                    bundle.putParcelable(Constants.KEY_USER_MARKER, user_markers.get(id_user));
                    userFragment.setArguments(bundle);
                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.container1, userFragment);
                    fragmentTransaction.commit();
                } catch (IndexOutOfBoundsException e) {
                    Log.e("IndexOutOfBoundsException", e.toString());
                    e.printStackTrace();
                }
                return false;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

}
